package com.retail.bbq.cola.aop;

import com.alibaba.excel.util.StringUtils;
import com.retail.bbq.cola.annotation.CheckHeader;
import com.retail.bbq.cola.constant.RedisConstant;
import com.retail.bbq.cola.enums.ErrorCodeEnum;
import com.retail.bbq.cola.exception.BadRequestException;
import com.retail.bbq.cola.utils.HeaderUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Aspect
@Component
public class HeaderCheckAspect {
    @Resource
    private RedisTemplate redisTemplate;
    public static final String Authorization = "Authorization";
    public static final String BU_CODE = "buCode";
    public static final String CODE = "Code";

    @Before("@annotation(checkHeader)")
    public void checkHeader(JoinPoint joinPoint, CheckHeader checkHeader) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        for (String header : checkHeader.requiredHeaders()) {
            if(header.equals(Authorization) && StringUtils.isEmpty(request.getHeader(header))){
                String redisUserTokenKey = String.format(RedisConstant.REDIS_KEY_USER_TOKEN,
                        request.getHeader(BU_CODE),
                        request.getHeader(CODE));
                //去缓存中查看是否有当前角色的Authorization值，有的话替换对应的值
                Object cacheValue = redisTemplate.opsForValue().get(redisUserTokenKey);
                if(Objects.isNull(cacheValue) || StringUtils.isBlank(cacheValue.toString())){
                    throw new BadRequestException(ErrorCodeEnum.PARAM_ERROR.getCode(),"缺少必要的请求头: " + header);
                }
                // 检查并添加需要补充的请求头信息
                request = HeaderUtils.addHeaderIfMissing(request, Authorization, cacheValue.toString());
            }else if (StringUtils.isEmpty(request.getHeader(header))) {
                throw new BadRequestException(ErrorCodeEnum.PARAM_ERROR.getCode(),"缺少必要的请求头: " + header);
            }
        }
    }
}
